#include "Render/TriMeshRenderable.h"
#include "Geom/TriMesh.h"

#include <glut.h>

namespace vital {

	//--------------------------------------------------------------------------
	TTriMeshRenderable::TTriMeshRenderable(TTriMesh *mesh) : 
		mTriMesh(mesh) 
		{
	}

	//--------------------------------------------------------------------------
	TTriMeshRenderable::~TTriMeshRenderable() {

		if(mTriMesh) {

			delete mTriMesh;
			mTriMesh = NULL;
		}
	}

	//--------------------------------------------------------------------------
	void TTriMeshRenderable::render() {

		if(!mTriMesh)
			return;

		const size_t faceCnt = mTriMesh->getFaceCnt();
		const size_t faceCntx3 = faceCnt * 3;

		const TTriMesh::IndexList &indices = mTriMesh->getIndices();
		const TTriMesh::Vec3List &positions = mTriMesh->getPositions();
		const TTriMesh::Vec3List &normals = mTriMesh->getNormals();
		const TTriMesh::Vec2List &tc2_0s = mTriMesh->getTexcoords2(0);

		bool hasNormals = !normals.empty();
		bool hasTexcoords = !tc2_0s.empty();

		if( !indices.empty() ) {

			glBegin(GL_TRIANGLES);
			
			for(size_t i=0; i<faceCntx3; ++i) {

				TTriMesh::VertexIndex vIdx = indices[i];

				if(hasTexcoords) glTexCoord2fv( tc2_0s[vIdx].getData() );
				if(hasNormals) glNormal3fv( normals[vIdx].getData() );
				glVertex3fv( positions[vIdx].getData() );

			}
			
			glEnd();

		} else {

			glBegin(GL_TRIANGLES);

			for(size_t i=0; i<faceCntx3; ++i) {

				if(hasTexcoords) glTexCoord2fv( tc2_0s[i].getData() );
				if(hasNormals) glNormal3fv( normals[i].getData() );
				glVertex3fv( positions[i].getData() );

			}
			
			glEnd();

		}
	}

	//--------------------------------------------------------------------------

}